local global   = require "global"
local mysql    = require "mysql"
local cjson    = require "cjson"
local genid    = require "genid"
local redis    = require "redis"
local mongo    = require "mongo"
 
ngx.header['Content-Type'] = 'application/json; charset=utf-8'
local arg   =   ngx.req.get_uri_args()

local body = ngx.req.get_body_data()
ngx.log(ngx.INFO,"body=======================>",body)
local ok, req_data = pcall(cjson.decode,body)
if not ok then
    return ngx.say(cjson.encode({errcode=10000, errmsg="系统繁忙", data={}}))
end

local order_no = req_data.order_no
if not order_no then
    return ngx.say(cjson.encode({errcode=10001, errmsg="参数错误", data={}}))
end

local mgo = mongo:new(global.get_mongo_conf())
local db  = mgo:new_db_handle("leshusanguo")
local col = db:get_col("recharge_order")
local order = col:find_one({order_no=order_no})

if not order then
    return ngx.say(cjson.encode({errcode=10002, errmsg="订单号错误", data={}}))
end

if order.pay_status == 1 then
    return ngx.say(cjson.encode({errcode=10003, errmsg="支付成功", data={}}))
end

print("order = ",order.uid)
print("order_no = ",order.order_no)
print("description= ",order.description)

-- 定义文件路径
local file_path = "/home/config.json"
-- 读取文件
local function read_json_file(file_path)
    local file, err = io.open(file_path, "r")  -- 打开文件进行读取
    if not file then
        ngx.log(ngx.ERR, "Failed to open config file: ", err)
        return nil
    end
    local content = file:read("*a")  -- 读取文件内容
    file:close()
    
    local data, decode_err = cjson.decode(content)  -- 解析 JSON
    if not data then
        ngx.log(ngx.ERR, "Failed to decode JSON: ", decode_err)
        return nil
    end
    return data
end

-- 查询用户当天充值金额
-- 获取今天的日期 (YYYY-MM-DD 格式)
local today = os.date("%Y-%m-%d")
local cursor = col:find({uid = order.uid, pay_status = 1, pay_at = { ["$regex"] = today }})  -- 执行查询
local total_amount = 0
if cursor  then 
    -- 手动迭代游标
    while true do
        local _, doc = cursor:next()  -- 使用下划线忽略索引，只获取文档
        if not doc then
            break  -- 如果没有更多记录，退出循环
        end
        total_amount = total_amount + (doc.payment or 0)  -- 累加充值金额
    end
    ngx.log(ngx.INFO, "User ID: ", order.uid, ", Today's Total Recharge: ", total_amount)
end

-- 获取配置数据
local max_payment_amount = 1000;
local is_vip=false
local config_data = read_json_file(file_path)
if config_data then
    max_payment_amount=config_data.pay.max_payment_amount
    local vip_list=config_data.vip
    for _, vip_id in ipairs(vip_list) do
        if order.uid == vip_id then
            is_vip = true
            break
        end
    end
end

if not is_vip and total_amount > max_payment_amount then
    ngx.log(ngx.INFO, "Total recharge amount exceeds Max, returning early.")
    local success, err = col:delete({order_no=order_no}, 1)  -- 删除订单（single_remove = 1）
    if not success then
        ngx.log(ngx.ERR, "Failed to delete order: ", err)
    end
    return ngx.say(cjson.encode({errcode=10002, errmsg="已超出今日最大金额", data={}}))
end

 
local col = db:get_col("user")
local user = col:find_one({uid=order.uid})
if user.parent_id and user.parent_id ~= "" then
    local r = redis:new(global.get_redis_conf())
    local k = string.format("%s:agent:bili", tostring(global.get_appname()))
    local bili = r:get(k) or 0
    local money = tonumber(bili) * order.payment
    local col = db:get_col("agent")
    col:update({_id=user.parent_id},{["$inc"]={money=money}})

    local log={
        order_no=order_no,
        uid=order.uid,
        agent_id=user.parent_id,
        money=money,
        description=order.description,
        payment=order.payment,
        created_at=os.date("%Y-%m-%d %H:%M:%S")
    }
    local col = db:get_col("order_rebate_log")
    local r, err = col:insert({log}, nil, true)
    if not r then ngx.say(cjson.encode({errcode=0, errmsg="insert failed err ".. err , data={}})) return end
end

local r = redis:new(global.get_redis_queue_conf())
local queuename= "leshusanguo:pay:queue"
local cmd={
    uuid=genid.genuuid(),
    order_no=order_no,
    uid=order.uid,
}
r:lpush(queuename, cjson.encode(cmd))

local col = db:get_col("recharge_order")
col:update({order_no=order_no},{["$set"]={pay_status=1, pay_at=os.date("%Y-%m-%d %H:%M:%S")}})

mgo:set_keepalive(10000, 100)
ngx.say(cjson.encode({errcode=0, errmsg="callback success", data={}}))